package drone.basis.util ;

import java.io.StringReader ;
import java.util.HashMap ;
import java.util.Map ;

import javax.xml.parsers.DocumentBuilder ;
import javax.xml.parsers.DocumentBuilderFactory ;

import org.w3c.dom.Document ;
import org.w3c.dom.Element ;
import org.w3c.dom.Node ;
import org.w3c.dom.NodeList ;
import org.xml.sax.InputSource ;

public class XmlUtil
{

	// 简单节点解析xml为map
	public static Map < String , String > parseXml (
			String xml
	)
	{
		Map < String , String > map = new HashMap < String , String > ( ) ;
		try
		{
			StringReader sr = new StringReader ( xml ) ;
			InputSource is = new InputSource ( sr ) ;
			DocumentBuilder builder = DocumentBuilderFactory.newInstance ( ).newDocumentBuilder ( ) ;
			Document doc = builder.parse ( is ) ;
			Element root = doc.getDocumentElement ( ) ;
			NodeList nodeList = root.getChildNodes ( ) ;
			for ( int i = 0 ; i < nodeList.getLength ( ) ; i ++ )
			{
				Node node = nodeList.item ( i ) ;
				map.put ( node.getNodeName ( ) , node.getTextContent ( ) ) ;
			}
			return map ;
		} catch ( Exception e )
		{
			return new HashMap < String , String > ( ) ;
		}
	}

	public static void main (
			String [ ] args
	) throws Exception
	{
		String xml = "<?xml version='1.0' encoding='UTF-8'?><respon><merNo>60187</merNo><gatewayNo>60817001</gatewayNo><tradeNo>T2017072612535059136654</tradeNo><orderNo>966196990991</orderNo><orderAmount>23246</orderAmount><orderCurrency>CNY</orderCurrency><orderStatus>0</orderStatus><orderErrorCode>I0004</orderErrorCode><orderInfo>I0004:Gateway of Merchant No.is incorrect</orderInfo><paymentMethod>Credit Card</paymentMethod><returnType>2</returnType><billAddress></billAddress><signInfo></signInfo><remark></remark><quickPayNo></quickPayNo></respon>" ;
		Map < String , String > doc = parseXml ( xml ) ;
		System.out.println ( doc ) ;
		System.out.println ( doc.get ( "orderInfo" ) ) ;
	}
}
